"""
球队申请相关 API
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import or_, and_
from typing import List
from datetime import datetime
from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.schemas.team_application import (
    TeamApplicationCreate,
    TeamApplicationReview,
    TeamApplicationResponse
)
from app.schemas.common import ApiResponse, PageData
from app.schemas.message import MessageCreate
from app.models.team_application import TeamApplication, ApplicationStatus
from app.models.team import Team, TeamMember
from app.models.user import User
from app.models.message import Message
from app.utils.helpers import generate_id

router = APIRouter()


@router.post("/apply", response_model=ApiResponse[TeamApplicationResponse])
async def apply_to_team(
    application_data: TeamApplicationCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """申请加入球队"""
    # 检查球队是否存在
    team = db.query(Team).filter(Team.id == application_data.teamId).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    
    # 检查是否已经是队员
    if current_user.team_ids and application_data.teamId in current_user.team_ids:
        raise HTTPException(status_code=400, detail="您已经是该球队成员")
    
    # 检查是否有待审批的申请
    existing_application = db.query(TeamApplication).filter(
        TeamApplication.team_id == application_data.teamId,
        TeamApplication.applicant_id == current_user.id,
        TeamApplication.status == ApplicationStatus.PENDING
    ).first()
    
    if existing_application:
        raise HTTPException(status_code=400, detail="您已经提交过申请，请等待审批")
    
    # 创建申请
    application = TeamApplication(
        id=generate_id(),
        team_id=application_data.teamId,
        team_name=team.name,
        applicant_id=current_user.id,
        applicant_name=current_user.nick_name or current_user.phone,
        applicant_avatar=current_user.avatar,
        status=ApplicationStatus.PENDING,
        message=application_data.message
    )
    
    db.add(application)
    
    # 发送消息给队长
    captain_message = Message(
        id=generate_id(),
        user_id=team.captain_id,
        type="team_application",
        title="新的入队申请",
        content=f"{application.applicant_name} 申请加入球队「{team.name}」",
        extra_data={
            "applicationId": application.id,
            "teamId": team.id,
            "teamName": team.name,
            "applicantId": current_user.id,
            "applicantName": application.applicant_name,
            "applicantAvatar": application.applicant_avatar,
            "message": application_data.message
        }
    )
    db.add(captain_message)
    
    db.commit()
    db.refresh(application)
    
    return ApiResponse(data=TeamApplicationResponse(**application.to_dict()))


@router.post("/review", response_model=ApiResponse[TeamApplicationResponse])
async def review_application(
    review_data: TeamApplicationReview,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """审批入队申请（队长操作）"""
    # 获取申请
    application = db.query(TeamApplication).filter(
        TeamApplication.id == review_data.applicationId
    ).first()
    
    if not application:
        raise HTTPException(status_code=404, detail="申请不存在")
    
    # 检查权限（只有队长可以审批）
    team = db.query(Team).filter(Team.id == application.team_id).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    
    if team.captain_id != current_user.id:
        raise HTTPException(status_code=403, detail="只有队长可以审批申请")
    
    # 检查申请状态
    if application.status != ApplicationStatus.PENDING:
        raise HTTPException(status_code=400, detail="该申请已被处理")
    
    # 更新申请状态
    if review_data.approved:
        application.status = ApplicationStatus.APPROVED
        
        # 将申请人加入球队
        applicant = db.query(User).filter(User.id == application.applicant_id).first()
        if applicant:
            if not applicant.team_ids:
                applicant.team_ids = []
            if application.team_id not in applicant.team_ids:
                applicant.team_ids.append(application.team_id)
            
            # 创建 TeamMember 记录
            import json
            positions_str = None
            if applicant.positions:
                if isinstance(applicant.positions, list):
                    positions_str = json.dumps(applicant.positions)
                elif isinstance(applicant.positions, str):
                    positions_str = applicant.positions
            
            team_member = TeamMember(
                id=generate_id(),
                team_id=application.team_id,
                user_id=application.applicant_id,
                user_name=applicant.nick_name or "未知用户",
                avatar=applicant.avatar,
                positions=positions_str,
                role="member"
            )
            db.add(team_member)
            
            # 更新球队成员数
            team.member_count = team.member_count + 1
        
        message_title = "入队申请已通过"
        message_content = f"恭喜！您加入球队「{team.name}」的申请已通过"
    else:
        application.status = ApplicationStatus.REJECTED
        application.reject_reason = review_data.rejectReason
        
        message_title = "入队申请未通过"
        message_content = f"很遗憾，您加入球队「{team.name}」的申请未通过"
        if review_data.rejectReason:
            message_content += f"\n原因：{review_data.rejectReason}"
    
    application.reviewed_by = current_user.id
    application.reviewed_at = datetime.utcnow()
    
    # 发送消息给申请人
    applicant_message = Message(
        id=generate_id(),
        user_id=application.applicant_id,
        type="team_application_result",
        title=message_title,
        content=message_content,
        extra_data={
            "applicationId": application.id,
            "teamId": team.id,
            "teamName": team.name,
            "approved": review_data.approved,
            "rejectReason": review_data.rejectReason
        }
    )
    db.add(applicant_message)
    
    db.commit()
    db.refresh(application)
    
    return ApiResponse(data=TeamApplicationResponse(**application.to_dict()))


@router.get("/my-applications", response_model=ApiResponse[PageData[TeamApplicationResponse]])
async def get_my_applications(
    status: str = Query(None, description="申请状态: pending, approved, rejected"),
    page: int = Query(1, ge=1),
    pageSize: int = Query(10, ge=1, le=100),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取我的申请列表"""
    query = db.query(TeamApplication).filter(
        TeamApplication.applicant_id == current_user.id
    )
    
    if status:
        query = query.filter(TeamApplication.status == status)
    
    query = query.order_by(TeamApplication.created_at.desc())
    
    total = query.count()
    applications = query.offset((page - 1) * pageSize).limit(pageSize).all()
    
    application_list = [TeamApplicationResponse(**app.to_dict()) for app in applications]
    
    return ApiResponse(
        data=PageData(
            list=application_list,
            total=total,
            page=page,
            pageSize=pageSize,
            hasMore=total > page * pageSize
        )
    )


@router.get("/team-applications/{team_id}", response_model=ApiResponse[PageData[TeamApplicationResponse]])
async def get_team_applications(
    team_id: str,
    status: str = Query(None, description="申请状态: pending, approved, rejected"),
    page: int = Query(1, ge=1),
    pageSize: int = Query(10, ge=1, le=100),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取球队的申请列表（队长查看）"""
    # 检查权限
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(status_code=404, detail="球队不存在")
    
    if team.captain_id != current_user.id:
        raise HTTPException(status_code=403, detail="只有队长可以查看申请列表")
    
    query = db.query(TeamApplication).filter(
        TeamApplication.team_id == team_id
    )
    
    if status:
        query = query.filter(TeamApplication.status == status)
    
    query = query.order_by(TeamApplication.created_at.desc())
    
    total = query.count()
    applications = query.offset((page - 1) * pageSize).limit(pageSize).all()
    
    application_list = [TeamApplicationResponse(**app.to_dict()) for app in applications]
    
    return ApiResponse(
        data=PageData(
            list=application_list,
            total=total,
            page=page,
            pageSize=pageSize,
            hasMore=total > page * pageSize
        )
    )


@router.get("/pending-count", response_model=ApiResponse[int])
async def get_pending_application_count(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取待审批申请数量（队长查看）"""
    # 获取当前用户担任队长的所有球队
    captain_teams = db.query(Team).filter(Team.captain_id == current_user.id).all()
    team_ids = [team.id for team in captain_teams]
    
    if not team_ids:
        return ApiResponse(data=0)
    
    # 统计待审批申请数量
    count = db.query(TeamApplication).filter(
        TeamApplication.team_id.in_(team_ids),
        TeamApplication.status == ApplicationStatus.PENDING
    ).count()
    
    return ApiResponse(data=count)


@router.delete("/{application_id}", response_model=ApiResponse[str])
async def cancel_application(
    application_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """取消申请"""
    application = db.query(TeamApplication).filter(
        TeamApplication.id == application_id,
        TeamApplication.applicant_id == current_user.id
    ).first()
    
    if not application:
        raise HTTPException(status_code=404, detail="申请不存在")
    
    if application.status != ApplicationStatus.PENDING:
        raise HTTPException(status_code=400, detail="只能取消待审批的申请")
    
    application.status = ApplicationStatus.CANCELLED
    db.commit()
    
    return ApiResponse(data="取消成功")

